package tmt.usercenter.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import tmt.usercenter.web.Application;
import tmt.usercenter.web.domain.TmtAuthority;
import tmt.usercenter.web.domain.vo.MenuItem;
import tmt.usercenter.web.service.TmtAuthorityService;
import tmt.usercenter.web.utils.HttpServletRequestHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

/**
 * 基础组件
 * Created by Stark on 2017/3/2.
 */
@Component
public class BaseFrontController extends BaseController {

    @Autowired
    private TmtAuthorityService authorityService;

    /**
     * 设置 mall 和 store 到 session 中
     */
    @ModelAttribute
    public void initMenuList(HttpServletRequest request, Model model,
                             @AuthenticationPrincipal(expression = "userId") Long userId) {
        String uri = HttpServletRequestHelper.getValidUriForMenu(request.getContextPath(), request.getRequestURI());

        List<TmtAuthority> tmtAuthorities = authorityService.loadEntities(TmtAuthority.class, "findAuthoritiesByUserId",
                new Object[]{userId}, "1");

        List<MenuItem> list = TmtAuthority.getValidMenuTree(uri, request.getContextPath(),
                tmtAuthorities, Application.SYSTEM_ID, Collections.singletonList(" FRONT "), null, null);
        model.addAttribute("menus", list);
    }


}
